<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>
            <span>编码</span>&nbsp;
            <span>名称</span>&nbsp;
            <span>单价</span>&nbsp;
            <span>数量</span>&nbsp;
            <span>总价</span>&nbsp;
        </div>
        <div v-for="(cart,index) in carts" :key="cart.id">
            <span>{{index+1}}</span>&nbsp;
            <span>{{cart.name}}</span>&nbsp;
            <span>{{cart.price}}</span>&nbsp;
            <button @click="handleAdd(index)">+</button> <span> {{cart.quantity}}</span><button
                @click="handleSub(index)">-</button> &nbsp;
            <span>{{cart.price*cart.quantity}}</span>&nbsp;
        </div>
        <div>总价：￥{{totalPrice}}</div>
    </div>
    <script src="./vue.js"></script>
    <script>
        let vm = new Vue({
            el: "#app",
            methods: {
                handleAdd: function (index) {
                    this.carts[index].quantity += 1;
                },
                handleSub: function (index) {
                    if(this.carts[index].quantity-1<0){
                        alert("已经小于0,不能再减了");
                        return false;// 添加return 代码就不会接着往下执行
                    }
                    this.carts[index].quantity -= 1;
                },
            },
            /* 计算属性，本身也是一个属性，不过根据依赖，动态去变化;当依赖没有发生变化的时候
            返回的是之前缓存的值，这也是里面的一个优化点
            */
            computed: {
                totalPrice: function () {
                    // 返回的值，就是计算属性 totalPrice的值
                    // return 100;
                    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
                    return this.carts.reduce((previousValue, currentValue) => previousValue + currentValue.price * currentValue.quantity, 0)
                }
            },
            data: {
                carts: [
                    {
                        id: 1,
                        name: "apple",
                        price: 3,
                        quantity: 2
                    },
                    {
                        id: 2,
                        name: "pear",
                        price: 4,
                        quantity: 3
                    },
                    {
                        id: 3,
                        name: "banana",
                        price: 5,
                        quantity: 4
                    }
                ]
            }
        })
    </script>
</body>

</html>